package com.gy.hsim.netty.server;

import org.springframework.beans.factory.annotation.Autowired;

import com.google.protobuf.InvalidProtocolBufferException;
import com.gy.hsim.netty.proto.BserviceProto;
import com.gy.hsim.netty.proto.BserviceProto.BserviceEntity;
import com.gy.hsxt.uc.as.api.ent.IUCAsEntService;
import com.gy.hsxt.uc.search.api.IUCUserInfoSearchService;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * 服务 channel
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<Object> { // (1)
	
	/**
	 * A thread-safe Set  Using ChannelGroup, you can categorize Channels into a meaningful group.
	 * A closed Channel is automatically removed from the collection,
	 */
	public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {  // (2)
        Channel incoming = ctx.channel();
        
        // Broadcast a message to multiple Channels
        String msg = "[SERVER] - " + incoming.remoteAddress() + " 登陆成功\n";
        System.out.println(msg);
        BserviceProto.BserviceEntity.Builder builder = BserviceProto.BserviceEntity.newBuilder();
        builder.setImSystem(msg);
        incoming.writeAndFlush(builder.build().toByteArray());
        channels.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {  // (3)
        Channel incoming = ctx.channel();
        
        // Broadcast a message to multiple Channels
        System.out.println("[SERVER] - " + incoming.remoteAddress() + " 离开\n");
        
        // A closed Channel is automatically removed from ChannelGroup,
        // so there is no need to do "channels.remove(ctx.channel());"
    }
    
	protected void channelRead(ChannelHandlerContext ctx, BserviceProto.BserviceEntity s) { // (4)
    	System.out.println("wdf");

	}
  
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception { // (5)
        Channel incoming = ctx.channel();
		System.out.println("SimpleChatClient:"+incoming.remoteAddress()+"在线");
	}
	
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception { // (6)
        Channel incoming = ctx.channel();
		System.out.println("SimpleChatClient:"+incoming.remoteAddress()+"掉线");
	}
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 
    	Channel incoming = ctx.channel();
		System.out.println("SimpleChatClient:"+incoming.remoteAddress()+"异常");
        // 当出现异常就关闭连接
        cause.printStackTrace();
        ctx.close();
    }

	@Override
	protected void messageReceived(ChannelHandlerContext ctx,
			Object o) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("server~~ in");
		BserviceProto.BserviceEntity s = BserviceProto.BserviceEntity.parseFrom(((byte[])o));
    	Channel incoming = ctx.channel();
    	System.out.println(s.getImSystem());
        BserviceProto.BserviceEntity.Builder builder = BserviceProto.BserviceEntity.newBuilder();
        builder.setImSystem(s.getImSystem() + "--【server已读】");
    	System.out.println("s.ImSystem" + s.getImSystem());
    	for (Channel channel : channels) {
            if (channel != incoming){
                channel.writeAndFlush(builder.build().toByteArray());
            } else {
            	channel.writeAndFlush(builder.build().toByteArray());
            }
        }
	}
   
}